﻿#region LicenseHeader

// Copyright 2012 The Trustees of Indiana University.  All rights reserved.
// 
// The Indiana University licenses this file to you under the Apache License, 
// Version 2.0 (the "License"); you may not use this file except in compliance 
// with the License.  You may obtain a copy of the License at 
// 
// http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software 
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
//  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
// See the License for the specific language governing permissions and 
// limitations under the License.
// 
// @author Thilina Gunarathne (tgunarat@indiana.edu)

#endregion

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Runtime.CompilerServices;
using AzureMRCore.DataTypes;
using AzureMRCore.Primitives;
using Microsoft.WindowsAzure.StorageClient;

namespace AzureMRCore.InputFormat
{
    public class CachedShortMatrixFormat : IInputFormat<IntKey, MappedShortMatrixValue>, ICachedInputFormat
    {
        private Boolean _isKeyed;
        private int _height, _width, _row, _rowOffset;
        private long _size;
        private bool _isRead;
        private long _position;
        private MemoryMappedViewAccessor _accessor;

        #region ICachedInputFormat Members

        public long GetSize()
        {
            return _size;
        }

        public ICachedInputFormat GetCachedCopy()
        {
            CachedShortMatrixFormat inputFormat = new CachedShortMatrixFormat();
            inputFormat.Init(_accessor, _position, _size, _width, _height, _row, _rowOffset);
            return inputFormat;
        }

        #endregion

        private void Init(MemoryMappedViewAccessor accessor, long position, long size, int vectorLength,
                          int numVectors, int row, int rowOffset)
        {
            _accessor = accessor;
            _position = position;
            _size = size;
            _width = vectorLength;
            _height = numVectors;
            _row = row;
            _rowOffset = rowOffset;
            _isRead = false;
        }

        #region IInputFormat<IntKey,double[]> Members

        public void Init(string blobURI, CloudBlobClient blobClient)
        {
            CloudBlob fileBlob = blobClient.GetBlobReference(blobURI);
            fileBlob.FetchAttributes();
            long fileLength = fileBlob.Attributes.Properties.Length;
            string[] parts = blobURI.Split('/');
            string fileName = parts[parts.Length - 1];
            MemoryMappedFile _mmf = MemoryMappedFile.CreateOrOpen(fileName, fileLength);

            MemoryMappedViewStream viewStream = _mmf.CreateViewStream();
            fileBlob.DownloadToStream(viewStream);
            viewStream.Flush();
            viewStream.Close();

            _accessor = _mmf.CreateViewAccessor();
            _height = _accessor.ReadInt32(_position);
            _position += sizeof (Int32);
            _width = _accessor.ReadInt32(_position);
            _position += sizeof (Int32);
            _row = _accessor.ReadInt32(_position);
            _position += sizeof (Int32);
            _rowOffset = _accessor.ReadInt32(_position);
            _position += sizeof (Int32);
            _isKeyed = _accessor.ReadBoolean(_position);
            _position += sizeof (Boolean);

            // _isRead = true;
        }

        public void Init(string inputFile)
        {
            BinaryReader _reader = new BinaryReader(File.Open(inputFile, FileMode.Open));
            FileInfo file = new FileInfo(inputFile);
            _size = file.Length;
            _height = _reader.ReadInt32();
            _width = _reader.ReadInt32();
            _row = _reader.ReadInt32();
            _rowOffset = _reader.ReadInt32();
            _isKeyed = _reader.ReadBoolean();


            //_isKeyed = _reader.ReadBoolean();
            ReadAll(_reader);
            _reader.Close();
        }

        public void Init(IDictionary<int, BCastDataProduct> inputRecords)
        {
            throw new NotImplementedException();
        }

        public List<KeyValuePair<IntKey, MappedShortMatrixValue>> GetAllPairs()
        {
            MappedShortMatrixValue matrixValue = MappedShortMatrixValue.GetInstance(_accessor, _position, _height,
                                                                                    _width, _row, _rowOffset);
            var list = new List<KeyValuePair<IntKey, MappedShortMatrixValue>>
                           {
                               new KeyValuePair<IntKey, MappedShortMatrixValue>(IntKey.GetInstance(0),
                                                                                matrixValue)
                           };
            return list;
        }

        public IntKey GetCurrentKey()
        {
            IntKey intKey = new IntKey {Key = 0};
            return intKey;
        }

        public MappedShortMatrixValue GetCurrentValue()
        {
            return MappedShortMatrixValue.GetInstance(_accessor, _position, _height, _width, _row, _rowOffset);
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        public bool Next()
        {
            if (!_isRead)
            {
                _isRead = true;
                return true;
            }

            return false;
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        public bool HasNext()
        {
            return !(_isRead);
        }

        public void Close()
        {
        }

        #endregion

        private short[][] ReadAll(BinaryReader reader)
        {
            /*   while (_counter < _height)
            {
                short[] vector;
                if (_isKeyed)
                {
                    throw new NotImplementedException();
//                    vector = new short[_width + 1];
//                    int key = reader.ReadInt32();
//                    vector[_width] = key;
                }
                vector = new short[_width];
                for (var i = 0; i < _width; i++)
                {
                    vector[i] = reader.ReadInt16();
                }
                _values[_counter] = vector;
                _counter++;
            }
            return _values;*/
            return null;
        }
    }
}